import React from 'react';
import { connect } from 'dva';
import { Tree, Button, Table, Form, Input, Popconfirm } from 'antd';
import DepartmentModal from '../../components/sys/DepartmentModal';
const TreeNode = Tree.TreeNode;
const FormItem = Form.Item;

function Department({ dispatch, department, loading, form }) {

  const { getFieldDecorator, getFieldsValue, getFieldValue } = form;

  const columns = [{
    title: '部门名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  }, {
    title: '排序号',
    dataIndex: 'sort',
    key: 'sort',
    width: 100,
  }, {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    width: 300,
  },{
    title: '操作',
    key: 'operation',
    width: 100,
    render: (text, record) => (
        <span>
            {/* <DepartmentModal title="编辑部门" record={record} depts={department.deptTree} onOk={editHandler.bind(null, record.id_)}>
            <a>编辑</a>
            </DepartmentModal> */}
            <a onClick={onEditItem.bind(null, record)}>编辑部门</a>
            <span className="ant-divider" />
            <Popconfirm title="确认删除？" onConfirm={deleteHandler.bind(null, record.id_)}>
            <a>删除</a>
            </Popconfirm>
        </span>
    ),
  }];

  const pagination = {
    current:department.current,
    pageSize:department.currentSize,
    total: department.total,
    showSizeChanger: true,
    showTotal: (total => '共' + department.total + '条'),
    onShowSizeChange(current, size) {
      dispatch({
        type: 'department/qryDeptsByPid',
        payload: { ...getFieldsValue(),...{'pageNum':current, 'pageSize':size} },
      });
    },
    onChange(current) {
      dispatch({
        type: 'department/qryDeptsByPid',
        payload:{ ...getFieldsValue(),...{'pageNum': current, 'pageSize':department.currentSize} }
      });
    },
  };

  //编辑部门
  const onEditItem = (record) => {
      dispatch({
          type: 'department/qryById',
          payload:record,
      })
  }


  const onSelect = (info) => {
    if(info.length > 0){
      dispatch({
        type: 'department/qryDeptsByPid',
        payload: { ...getFieldsValue(),...{'pid':info[0]} },
      });
    }else{
      dispatch({
        type: 'department/qryDeptsByPid',
        payload: { ...getFieldsValue(),...{'pid':1} },
      });
    }
  }

  const loop = data => data.map((item) => {
      if (item.depts && item.depts.length) {
        return <TreeNode key={item.id_} title={item.name}>{loop(item.depts)}</TreeNode>;
      }
      return <TreeNode key={item.id_} title={item.name} />;
  });

  const submitHandle = () => {
    dispatch({
        type: 'department/qryDeptsByPid',
        payload: { ...getFieldsValue() },
    });
  }

  const editHandler = (id, values) => {
    dispatch({
      type: 'department/edit',
      payload: { id, ...values },
    });
  }

  function deleteHandler(id) {
    dispatch({
      type: 'department/remove',
      payload: {id:id,search:{...getFieldsValue()}},
    });
  }

  const onAdd = () => {
    dispatch({
      type: 'department/showModal',
      payload: {
        modalType: 'create',
      },
    })
  }

  const modalProps = {
    item: department.modalType === 'create' ? {} : department.currentItem,
    depts: department.deptTree,
    currentPid:department.pid,
    visible: department.modalVisible,
    type: department.modalType,
    maskClosable: false,
    confirmLoading: loading,
    title: `${department.modalType === 'create' ? '新增组织结构' : '更新组织结构'}`,
    wrapClassName: 'vertical-center-modal',
    newKey : department.newKey,
    onOk (data) {
      if(department.modalType=== 'create'){
          dispatch({
            type: 'department/create',
            payload: data,
            search:{...getFieldsValue(),...{'pid':data.pid,}}
          });
      }else{
          dispatch({
            type: 'department/edit',
            payload: { id, ...data },
          });
      }
     
    },
    onCancel () {
      dispatch({
        type: 'department/hideModal',
      })
    },
  }



  return (
    <div style={{backgroundColor:'#fff'}}>
      <div style={{width:'250px',float:'left'}}>
        <div style={{width:'100%',height:'40px',backgroundColor:'#232f40',lineHeight:'40px',color:'#fff',paddingLeft:'20px',fontSize:'14px',fontWeight:'400'}}>
          组织结构树
        </div>
        <div style={{width:'100%',}}>
          <Tree
            defaultExpandedKeys = {['1']}
            onSelect={onSelect}
          >           
            { department.deptTree && loop(department.deptTree) }
          </Tree>
        </div>
      </div>
      <div style={{minHeight:'100%',marginLeft:'250px'}}>
        <div style={{width:'100%',backgroundColor:'#fff',lineHeight:'40px',paddingLeft:'20px',paddingTop:'10px'}}>
          <Form layout="inline">
            <FormItem>
              {getFieldDecorator('pid',{initialValue:department.pid})(
                <Input type="hidden" />
              )}
            </FormItem>

            <FormItem>
              {getFieldDecorator('name',{initialValue:''})(
                <Input type="text" placeholder="部门名称" style={{ width:'200px', marginRight: '3%' }} />
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" size='large' onClick={submitHandle} className='ant-search-btn'>查询</Button>
            </FormItem>
            <div style={{marginTop:'-40px',textAlign:'right',paddingRight:'10px'}}>
              <FormItem>               
                  <Button type="primary" size='large' onClick={onAdd}>新增部门</Button>
              </FormItem>
            </div>
         </Form>
        </div>
        <div style={{width:'100%',padding:'30px 20px',}}>
          <Table columns={columns} rowKey={record => record.id_} loading={loading} dataSource={department.deptList} pagination={pagination}
          />
        </div>
        <div style={{width:'100%',clear:'both'}}></div>
        <DepartmentModal {...modalProps} />
      </div>
    </div>
  );
}

function mapStateToProps(state) {
  return { department : state.department,loading:state.loading.models.department};
}

Department = Form.create()(Department);

export default connect(mapStateToProps)(Department);
